package com.example.administrator.commonlibrary.bese;


import android.util.Log;

import com.example.administrator.commonlibrary.networkframework.consumer.MyAction;
import com.example.administrator.commonlibrary.networkframework.consumer.MyConsumer;
import com.example.administrator.commonlibrary.networkframework.RetrofitClient;
import com.example.administrator.commonlibrary.networkframework.RetrofitInterface;
import com.example.administrator.commonlibrary.utils.LogUtil;
import com.example.administrator.commonlibrary.utils.NetUtils;
import com.example.administrator.commonlibrary.utils.rxjava.RxBus;

import org.reactivestreams.Subscription;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * @author wang_hong_wei
 * @description MVP Activity 解绑的基类
 * CompositeDisposable  的使用https://www.jianshu.com/p/b672724dbff8
 * @Date 2018-5-31
 */
public abstract class BasePresenterImpl<T extends BaseContract.BaseView> implements BaseContract.BasePresenter<T> {
    protected Reference<T> mViewRef;//view接口类型的弱引用
    protected CompositeDisposable mCompositeDisposable;

    protected RetrofitInterface flowable;
    private Action action;
    protected T mView;

    @Override
    public void attachView(T view) {
        mView=view;
        mViewRef = new SoftReference<T>(view);//建立关联
        daggerInject(null);
        flowable = RetrofitClient.getInstance().create(RetrofitInterface.class);       //retrofit初始化
        mCompositeDisposable = new CompositeDisposable();
        setSubscription(addSubscription());//用Rxjava2 发送消息 在子类中重写此方法就可以addSubscription()
        attachView();
    }

    @Override
    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
        cancelRequest();
    }

    @Override
    public void cancelRequest() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    protected <K> void daggerInject(K module) {
    }

    ;//用于实例化presenter层对象在attachView 之前运行，防止报null

    protected T getView() {
        return mViewRef.get();
    }

    /*
     * 运行在 Activity 的onCreate()生命周期中
     * 在网络请求对象之后 可以再这个方法里直接请求网络(如果实在Fragment里，不建议在此方法中请求网络)
     * */
    protected abstract void attachView();

    /*
     * 判断 是否解绑
     * */
    public boolean isViewAttached() {
        return mViewRef != null && mViewRef.get() != null;
    }

    public void addSubscription(Flowable observable, final MyConsumer consumer) {
        if (mCompositeDisposable == null) {
          throw new NullPointerException("mCompositeDisposable 不能为null-----");
        }

        Consumer synthesis = new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                if (o instanceof Throwable) {
                    getMessage((Throwable) o, consumer);
                } else if (o instanceof Subscription) {
                    ((Subscription) o).request(Long.MAX_VALUE);//Rxjava2 被压策略
                } else {
                    consumer.onNoxt(o);
                }
            }
        };
        mCompositeDisposable.add(observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(synthesis, synthesis, MyAction.getInstance(), synthesis));
    }

    public void getMessage(Throwable e, MyConsumer consumer) {
        LogUtil.e(e.toString());
        if (e instanceof retrofit2.HttpException) {
            retrofit2.HttpException httpException = (retrofit2.HttpException) e;
            int code = httpException.code();
            String msg = httpException.getMessage();
            if (httpException.response().toString() == null) {
                msg = "请重新登录";
            }
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 500) {
                msg = "请求失败";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            if (consumer != null) consumer.onError(msg);
        } else {
            if (!NetUtils.isNetworkConnected(BaseAppliction.getBaseAppliction())) {
                if (consumer != null) consumer.onError("(╯▽╰)加载不出来...好像\\n没网啦...");
            }
            mView.dismissLoadingDialog();
        }
    }

    public Consumer addSubscription() {
        return null;
    }

    private void setSubscription(Consumer consumer) {
        if (consumer == null) return;
        if (mCompositeDisposable == null) {
            throw new NullPointerException("mCompositeDisposable 不能为null-----");
        }
        mCompositeDisposable.add(RxBus.getInstance().toObservable(Object.class).subscribe(consumer));
    }


}
